package com.lm.activiti.boot.tools;

import com.lowagie.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author lm_jcf
 * @date 2019/7/4 14:03
 */
public class HtmlConvertPdfUtils {

    public static Boolean HtmlCovertPdf(String inputFile, String outFile) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(outFile);
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            //处理中文
            fontResolver.addFont(ClassLoader.getSystemClassLoader().getResource("").getPath() + "\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//            fontResolver.addFont(ClassLoader.getSystemClassLoader().getResource("").getPath() + "\\msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//            fontResolver.addFont("c:\\Windows\\Fonts\\msyhl.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            String url = new File(inputFile).toURI().toURL().toString();

            renderer.setDocument(url);
            renderer.layout();
            renderer.createPDF(os);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                os.close();
                System.out.println(outFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        HtmlConvertPdfUtils pdfUtils = new HtmlConvertPdfUtils();
        File rootFile = new File(pdfUtils.getClass().getResource("").getPath());
//        String path = rootFile.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getPath();

//        String originUrl = "htmlConvertPdf.html";
//        String originUrl = path + "\\html\\test.html";
//        String originUrl = path + "\\html\\teststs.html";
      /*  String originUrl = path + "\\html\\teststs2.html";


        String targetUrl = path + "\\htmlConvertPdf.pdf";
        HtmlCovertPdf(originUrl, targetUrl);*/

//        String o = "C:\\Users\\lm_jcf\\Desktop\\html1.html";
        String o = "C:\\Users\\lm_jcf\\Desktop\\考场表—1.html";

        String t = "C:\\Users\\lm_jcf\\Desktop\\html1.pdf";
        HtmlCovertPdf(o, t);
    }


}
